<template>
  <div class="body">
    <div class="body_left">
      <div class="body_left_header">
        <div
          class="half"
          :class="
            leftActiveType === item.type
              ? 'half-active'
              : ''
          "
          v-for="item in typeList"
          :key="item.type"
          @click="typeClick(item)"
        >
          <div style="display: inline-block">
            <Icon
              :name="item.icon"
              :color="
                leftActiveType === item.type
                  ? '#497FA3'
                  : '#4c565c'
              "
              font-size="20"
            />
          </div>
          <span>{{ item.name }}</span>
        </div>
      </div>

      <div class="body_tree">
        <el-tree
          v-if="treeData.length > 0"
          ref="tree"
          :default-expand-all="true"
          :data="treeData"
          :expand-on-click-node="false"
          :current-node-key="activeTree && activeTree.pkid"
          node-key="pkid"
          highlight-current
          draggable
          @node-drop="handleDrop"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
        >
          <template slot-scope="{ node, data }">
            <div
              style="
                width: 100%;
                line-height: 36px;
                display: flex;
                align-items: center;
              "
              @click="onCatalogClick(data)"
            >
              <div
                style="
                  display: inline-block;
                  vertical-align: middle;
                  margin-right: 6px;
                "
              >
                <icon
                  :title="'文件夹'"
                  :name="
                    leftActiveType === '1'
                      ? 'wenjianjia'
                      : data.realName
                      ? 'tupian'
                      : 'wenjianjia'
                  "
                  font-size="16"
                  :color="
                    data.resourceInfo &&
                    data.resourceInfo.length > 0
                      ? '#0098ff'
                      : ''
                  "
                />
              </div>
              <div
                style="
                  display: inline-block;
                  vertical-align: middle;
                  white-space：nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  flex: 1;
                "
              >
                {{ data.label || data.fileName }}
              </div>
              <div
                style="
                  width: 40%;
                  display: inline-block;
                  line-height: 36px;
                  height: 36px;
                  vertical-align: middle;
                "
              >
                <i
                  @click.stop="deleteCatalog(data.pkid)"
                  class="el-icon-delete"
                  v-if="
                    leftActiveType === '1' ||
                    (leftActiveType === '2' &&
                      data.catalogName)
                  "
                  style="
                    font-size: 16px;
                    float: right;
                    margin-right: 20px;
                    color: #ff5b5b;
                    line-height: 36px;
                  "
                ></i>
                <i
                  @click.stop="editCatalog(data)"
                  class="el-icon-edit-outline"
                  v-if="
                    leftActiveType === '1' ||
                    (leftActiveType === '2' &&
                      data.catalogName)
                  "
                  style="
                    font-size: 16px;
                    float: right;
                    margin-right: 10px;
                    color: #00baff;
                    line-height: 36px;
                  "
                ></i>
                <i
                  @click.stop="addCatalog(data)"
                  class="el-icon-circle-plus-outline"
                  v-if="
                    (leftActiveType === '1' &&
                      data.parentId ===
                        attachmentRootCatalogId) ||
                    (leftActiveType === '2' &&
                      data.catalogName)
                  "
                  style="
                    font-size: 16px;
                    float: right;
                    margin-right: 10px;
                    color: #00baff;
                    line-height: 36px;
                  "
                ></i>
              </div>
            </div>
          </template>
        </el-tree>
        <div
          v-else
          style="display: flex; justify-content: center"
        >
          <i
            @click="addEmptyCatalog"
            class="el-icon-circle-plus-outline"
            style="
              cursor: pointer;
              font-size: 16px;
              color: #00baff;
              line-height: 36px;
            "
          ></i>
        </div>
      </div>
    </div>
    <div class="body_right">
      <div class="body_right_header">
        <el-button
          @click="serveAdd"
          :disabled="uploadButtonDisabled"
        >
          <div
            style="display: inline-block"
            class="el-icon-plus"
          ></div>
          <span style="margin-left: 4px">
            {{
              leftActiveType === '1'
                ? '附件上传'
                : !activeTree || activeTree.catalogName
                ? '图片上传'
                : '关联图片'
            }}
          </span>
        </el-button>
      </div>
      <el-table
        :data="serveList"
        :header-cell-style="{
          background: '#F2F6FB ',
          color: ' #6B767D'
        }"
        height="704px"
        ref="table"
        :row-class-name="tableRowClassName"
        row-key="pkid"
      >
        <el-table-column
          label="序号"
          align="center"
          show-overflow-tooltip
          width="80"
        >
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="leftActiveType === '2'"
          prop="type"
          label="图片类型"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="leftActiveType === '2'"
          prop="remark"
          label="图片说明"
          show-overflow-tooltip
        />
        <el-table-column
          prop="fileName"
          :label="
            leftActiveType === '1' ? '附件名称' : '图片名称'
          "
          show-overflow-tooltip
        />
        <el-table-column
          prop="releaseTime"
          label="发布时间"
          show-overflow-tooltip
          width="200"
        >
        </el-table-column>
        <el-table-column
          prop="realName"
          :label="leftActiveType === '1' ? '附件' : '图片'"
          show-overflow-tooltip
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="
                leftActiveType !== '2' ||
                activeTree.catalogName
              "
              type="text"
              @click="updateServe(scope.row)"
              style="
                color: #00baff;
                font-weight: 400;
                margin-right: 24px;
              "
              >编辑
            </el-button>
            <el-button
              type="text"
              @click="deleteServe(scope.row)"
              style="color: #ff5b5b; font-weight: 400"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        style="float: right; margin-top: 15px"
        v-if="total"
      >
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="parameter.pageSize"
          @current-change="pageChange"
          :total="total"
          :current-page.sync="parameter.pageIndex"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 目录 -->
    <el-dialog
      :visible.sync="dialogVisibleTree"
      :title="headerTreeTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="600px"
    >
      <el-form
        :model="treeForm"
        :rules="treeRules"
        v-if="dialogVisibleTree"
        label-width="100px"
        label-position="left"
        ref="ruleForm"
      >
        <el-form-item
          label="当前目录节点"
          v-if="headerTreeTitle !== '编辑目录'"
        >
          <el-cascader
            disabled
            placeholder="选择目录"
            style="width: 100%"
            clearable
            v-model="treeForm.parentId"
            :options="treeData"
            :props="{
              value: 'pkid',
              label: 'label',
              children: 'children',
              checkStrictly: true
            }"
          />
        </el-form-item>
        <el-form-item
          label="目录层级"
          prop="pidType"
          v-if="headerTreeTitle !== '编辑目录'"
        >
          <el-select
            v-model="treeForm.pidType"
            style="width: 100%"
            :disabled="leftActiveType === '2'"
          >
            <el-option
              label="子目录"
              :value="0"
            ></el-option>
            <el-option
              label="同级目录"
              :value="1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="catalogName">
          <el-input v-model="treeForm.catalogName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          @click="dialogVisibleTree = false"
          class="update"
          >取消
        </el-button>
        <el-button
          type="primary"
          @click="onAddCatalog('ruleForm')"
          >确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 空目录时添加目录 -->
    <el-dialog
      :visible.sync="emptyDialogVisibleTree"
      :title="headerTreeTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="600px"
    >
      <el-form
        :model="emptyTreeForm"
        :rules="emptyTreeRules"
        v-if="emptyDialogVisibleTree"
        label-width="100px"
        label-position="left"
        ref="emptyRuleForm"
      >
        <el-form-item label="目录名称" prop="catalogName">
          <el-input v-model="emptyTreeForm.catalogName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          @click="emptyDialogVisibleTree = false"
          class="update"
          >取消
        </el-button>
        <el-button
          type="primary"
          @click="onAddCatalog('emptyRuleForm')"
          >确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 附件上传 -->
    <el-dialog
      :visible.sync="attachmentDialogVisible"
      :title="headerServeTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="upload-dialog"
      width="600px"
      @close="dialogClosed"
    >
      <el-scrollbar>
        <el-form
          :model="serveForm"
          :rules="serveFormRules"
          v-if="attachmentDialogVisible"
          label-width="110px"
          label-position="left"
          ref="ruleFormServe"
        >
          <el-form-item label="目录节点" prop="stage">
            <el-input
              disabled
              v-model="serveForm.catalogName"
            />
          </el-form-item>
          <el-form-item
            v-if="!addServe"
            :label="
              leftActiveType === '1'
                ? '附件名称'
                : '图片名称'
            "
            prop="attachmentName"
          >
            <el-input
              v-model="serveForm.attachmentName"
              clearable
              :placeholder="
                leftActiveType === '1'
                  ? '请输入附件名称'
                  : '请输入图片名称'
              "
            />
          </el-form-item>
          <el-form-item
            v-if="!addServe && leftActiveType === '2'"
            label="图片说明"
            prop="remark"
          >
            <el-input
              v-model="serveForm.remark"
              clearable
              placeholder="请输入图片说明"
            />
          </el-form-item>
          <el-form-item
            v-if="!addServe"
            label="发布时间"
            prop="releaseTime"
          >
            <el-date-picker
              v-model="serveForm.releaseTime"
              type="datetime"
              placeholder="请选择发布时间"
              :default-time="
                parseDateTime(serveForm.releaseTime)
              "
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="addServe"
            :label="
              leftActiveType === '1'
                ? '选择附件'
                : '选择图片'
            "
          >
            <el-upload
              ref="upload"
              :auto-upload="false"
              :show-file-list="false"
              :file-list="uploadList"
              :on-change="handleUploadListChange"
              :on-remove="handleUploadListRemove"
              action=""
              :accept="
                leftActiveType === '1' ? '.pdf' : 'image/*'
              "
              multiple
            >
              <span slot="trigger">
                <el-button type="primary"> 上传 </el-button>
                <span
                  >（{{
                    leftActiveType === '1' ? '20' : '10'
                  }}MB以内）</span
                >
              </span>

              <div
                v-for="item in uploadList"
                :key="item.uid"
              >
                <i
                  v-if="item.fileId"
                  class="el-icon-circle-check"
                  style="color: green"
                ></i>
                <span>{{ item.name }}</span>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <el-button
          @click="attachmentDialogVisible = false"
          class="update"
          >取消
        </el-button>
        <el-button type="primary" @click="onSubmitServe"
          >确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 关联图片 -->
    <el-dialog
      :visible.sync="relationPictureDialogVisible"
      :title="headerServeTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="upload-dialog"
      width="600px"
      @close="relationPictureDialogClosed"
    >
      <el-scrollbar>
        <el-tree
          ref="tree"
          :default-expand-all="true"
          :data="deepClonedTreeData"
          :expand-on-click-node="true"
          node-key="pkid"
          highlight-current
        >
          <template slot-scope="{ node, data }">
            <div
              style="
                width: 100%;
                line-height: 36px;
                display: flex;
                align-items: center;
              "
            >
              <el-checkbox
                :key="data.pkid"
                v-if="
                  !data.catalogName &&
                  !(
                    activeTree &&
                    activeTree.pkid === data.pkid
                  )
                "
                :disabled="
                  defaultCheckedIds.indexOf(data.pkid) !==
                  -1
                "
                v-model="data.checked"
                style="margin-right: 6px"
              />
              <div
                style="
                  display: inline-block;
                  vertical-align: middle;
                  margin-right: 6px;
                "
              >
                <icon
                  :title="'文件夹'"
                  :name="
                    leftActiveType === '1'
                      ? 'wenjianjia'
                      : data.realName
                      ? 'baseMap'
                      : 'wenjianjia'
                  "
                  font-size="16"
                  :color="
                    data.resourceInfo &&
                    data.resourceInfo.length > 0
                      ? '#0098ff'
                      : ''
                  "
                />
              </div>
              <div
                style="
                  display: inline-block;
                  vertical-align: middle;
                  white-space：nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  flex: 1;
                "
              >
                {{ data.label || data.fileName }}
              </div>
            </div>
          </template>
        </el-tree>
      </el-scrollbar>
      <template #footer>
        <el-button
          @click="relationPictureDialogVisible = false"
          class="update"
          >取消
        </el-button>
        <el-button
          type="primary"
          @click="onRelationPictureSubmit"
          >确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  treeByTypeId,
  treeAdd,
  treeUpdate,
  treeDelete
} from '@/api/tree'
import {
  addAttachmentToCatalog,
  retrieveAttachmentInCatalog,
  updateAttachmentInCatalog,
  updateAttachmentOrderInCatalog,
  deleteAttachmentInCatalog,
  retrievePictureInRelation,
  addPictureInRelation,
  deletePictureInRelation,
  updateRelationPicturesOrder
} from '@/api/multiple-dataservice'
import { noticeFileUpload } from '@/api/wisdomBuild'
import Sortable from 'sortablejs'
import Icon from '@/components/icon'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash'

let _sortable

export default {
  name: 'index',
  components: {
    Icon
  },
  data() {
    return {
      typeList: [
        { name: '附件资料', type: '1', icon: 'shujumulu' },
        { name: '图片', type: '2', icon: 'zhuantileixing' }
      ],
      leftActiveType: '1',
      // 目录树数据
      treeData: [],
      treeActiveData: null,
      activeTree: null,
      currentAttachment: null,
      // 附件数据
      serveList: [],
      total: 0,
      parameter: {
        catalogId: '',
        pageSize: 10,
        pageIndex: 1
      },
      headerTreeTitle: '',
      headerServeTitle: '',
      add: true,
      addServe: true,
      treeForm: {
        catalogName: '',
        parentId: '',
        pidType: 0
      },
      emptyTreeForm: {
        catalogName: ''
      },
      treeRules: {
        catalogName: [
          {
            required: true,
            message: '请输入目录名称',
            trigger: 'blur'
          }
        ],
        pidType: [
          {
            required: true,
            message: '请选择目录层级',
            trigger: 'change'
          }
        ]
      },
      emptyTreeRules: {
        catalogName: [
          {
            required: true,
            message: '请输入目录名称',
            trigger: 'blur'
          }
        ]
      },
      dialogVisibleTree: false,
      emptyDialogVisibleTree: false,
      serveForm: {
        catalogName: '',
        attachmentName: '',
        releaseTime: '',
        remark: ''
      },
      serveFormRules: {
        attachmentName: [
          {
            required: false,
            message: '请输入文件名称',
            trigger: 'blur'
          }
        ],
        releaseTime: [
          {
            required: false,
            message: '请选择发布时间',
            trigger: 'blur'
          }
        ]
      },
      attachmentDialogVisible: false,
      defaultList: [],
      dataConfigInfo: null,
      attachmentRootCatalogId: '',
      uploadList: [],
      relationPictureDialogVisible: false,
      defaultCheckedIds: [],
      dragMode: 'list' // list: 列表目录, relation: 关联关系目录
    }
  },
  mounted() {
    this.dataConfigInfo = JSON.parse(
      localStorage.getItem('dataServiceWithValue')
    )
    this.getCatalogTree(
      `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
    )
  },
  methods: {
    handleUploadListChange(file, fileList) {
      this.uploadList = fileList
    },
    handleUploadListRemove(file, fileList) {
      this.uploadList = fileList
    },
    typeClick(item) {
      this.leftActiveType = item.type
      this.activeTree = null
      this.treeActiveData = null
      this.serveList = []
      this.treeData = []
      this.attachmentRootCatalogId = ''
      this.getCatalogTree(
        this.leftActiveType === '1'
          ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
          : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
      )
    },
    // el-pagination分页改变
    pageChange(page) {
      this.parameter.pageIndex = page
      this.getServeList()
    },
    // 获取目录树
    getCatalogTree(type) {
      treeByTypeId(type).then((res) => {
        if (res.success) {
          if (res.data) {
            if (res.data.length) {
              const tempTreeData = res.data[0].children
              tempTreeData.forEach(
                (item) => (item.label = item.catalogName)
              )
              this.treeData = tempTreeData
              this.attachmentRootCatalogId =
                res.data[0].pkid
              if (this.leftActiveType === '1') {
                this.addResourceInfo(this.treeData)
              } else {
                // 如果是图片tab，则查询所有目录下的图片
                this.treeData.forEach((item) => {
                  retrieveAttachmentInCatalog({
                    catalogId: item.pkid,
                    pageIndex: 1,
                    pageSize: 9999
                  })
                    .then((res) => {
                      if (res.success) {
                        if (res.data.list.length) {
                          item.children = res.data.list
                        }
                      } else {
                        this.$message.error(res.message)
                      }
                    })
                    .catch((err) => {
                      console.error(err)
                    })
                })
              }
            } else {
              this.addRootCatalog()
            }
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 添加或获取根目录
    addRootCatalog() {
      treeAdd({
        catalogName: '根目录',
        parentId: -1,
        type:
          this.leftActiveType === '1'
            ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
            : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
      }).then((res) => {
        if (res.success) {
          this.attachmentRootCatalogId = res.data
        }
      })
    },
    addResourceInfo(data) {
      data.forEach((item) => {
        if (item.children && item.children.length) {
          item.children.forEach((child) => {
            child.label = child.catalogName
          })
        }
      })
    },
    // 目录树点击
    onCatalogClick(item) {
      if (this.leftActiveType === '1') {
        this.parameter.pageIndex = 1
        this.activeTree = item
        if (
          this.activeTree &&
          this.activeTree.parentId !==
            this.attachmentRootCatalogId
        ) {
          this.getServeList()
        } else {
          this.serveList = []
        }
      } else {
        this.parameter.pageIndex = 1
        this.activeTree = item
        if (this.activeTree.catalogName) {
          this.getServeList()
        } else {
          this.getRelationPicture()
        }
      }
    },
    addCatalog(data) {
      this.headerTreeTitle = '新增目录'
      this.treeForm.catalogName = ''
      this.treeActiveData = data
      this.treeForm.parentId = data.pkid
      this.treeForm.pidType =
        this.leftActiveType === '1' ? 0 : 1
      this.dialogVisibleTree = true
      this.add = true
    },
    addEmptyCatalog() {
      this.headerTreeTitle = '新增目录'
      this.emptyTreeForm.catalogName = ''
      this.emptyDialogVisibleTree = true
      this.add = true
    },
    editCatalog(item) {
      this.headerTreeTitle = '编辑目录'
      this.treeActiveData = item
      this.treeForm.catalogName = item.catalogName
      this.treeForm.parentId = item.parentId
      this.treeForm.pkid = item.pkid
      this.dialogVisibleTree = true
      this.add = false
    },
    deleteCatalog(id) {
      this.$confirm(
        '此操作将永久删除该目录，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        treeDelete(id).then((res) => {
          if (res.success) {
            this.dialogVisibleTree = false
            this.$message.success('删除目录成功')
            this.activeTree = null
            this.treeActiveData = null
            this.getCatalogTree(
              this.leftActiveType === '1'
                ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
                : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
            )
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    onAddCatalog(ruleForm) {
      this.$refs[ruleForm].validate((vaild) => {
        if (vaild) {
          if (ruleForm === 'emptyRuleForm') {
            treeAdd({
              parentId: this.attachmentRootCatalogId,
              catalogName: this.emptyTreeForm.catalogName,
              type:
                this.leftActiveType === '1'
                  ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
                  : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
            }).then((res) => {
              if (res.success) {
                this.emptyDialogVisibleTree = false
                this.$message.success('新增目录成功')
                this.getCatalogTree(
                  this.leftActiveType === '1'
                    ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
                    : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
                )
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            if (this.add) {
              if (
                this.treeData
                  .map((item) => item.catalogName)
                  .indexOf(this.treeForm.catalogName) !== -1
              ) {
                this.$message.error('图片类型不能重复')
                return
              }
              treeAdd({
                parentId: this.treeForm.pidType
                  ? this.treeActiveData.parentId
                  : this.treeForm.parentId,
                catalogName: this.treeForm.catalogName,
                type:
                  this.leftActiveType === '1'
                    ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
                    : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
              }).then((res) => {
                if (res.success) {
                  this.dialogVisibleTree = false
                  this.$message.success('新增目录成功')
                  this.getCatalogTree(
                    this.leftActiveType === '1'
                      ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
                      : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
                  )
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              treeUpdate(
                {
                  parentId: this.treeForm.parentId,
                  catalogName: this.treeForm.catalogName,
                  type:
                    this.leftActiveType === '1'
                      ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
                      : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
                },
                this.treeForm.pkid
              ).then((res) => {
                if (res.success) {
                  this.dialogVisibleTree = false
                  this.$message.success('编辑目录成功')
                  this.getCatalogTree(
                    this.leftActiveType === '1'
                      ? `${this.dataConfigInfo.pkid}--${this.dataConfigInfo.attributeValue}`
                      : `${this.dataConfigInfo.pkid}__${this.dataConfigInfo.attributeValue}`
                  )
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          }
        }
      })
    },
    serveAdd() {
      if (
        this.leftActiveType === '1' ||
        !this.activeTree ||
        this.activeTree.catalogName
      ) {
        // 附件或图片上传
        this.headerServeTitle =
          this.leftActiveType === '1'
            ? '附件上传'
            : '图片上传'
        if (!this.activeTree || !this.activeTree.pkid) {
          this.$message.warning(
            `请先选择数据目录，再挂载${
              this.leftActiveType === '1' ? '文件' : '图片'
            }`
          )
          return
        }
        this.addServe = true
        this.serveForm.catalogName =
          this.activeTree.catalogName
        this.serveForm.attachmentName = ''
        this.serveForm.remark = ''
        this.serveForm.releaseTime = ''
        this.serveFormRules.attachmentName[0].required = false
        this.serveFormRules.releaseTime[0].required = false
        this.attachmentDialogVisible = true
      } else {
        // 选择关联图片
        this.headerServeTitle = '关联图片'
        this.defaultCheckedIds = this.serveList.map(
          (item) => item.pkid
        )
        this.deepClonedTreeData.forEach((item) => {
          item.children.forEach((picture) => {
            if (
              this.defaultCheckedIds.indexOf(
                picture.pkid
              ) !== -1
            ) {
              picture.checked = true
            }
          })
        })
        this.relationPictureDialogVisible = true
      }
    },
    async updateServe(data) {
      this.headerServeTitle = '编辑附件'
      this.addServe = false

      this.currentAttachment = data
      this.serveForm.catalogName =
        this.activeTree.catalogName
      this.serveForm.attachmentName = data.fileName
      this.serveForm.remark = data.remark
      this.serveForm.releaseTime = data.releaseTime
      this.serveFormRules.attachmentName[0].required = true
      this.serveFormRules.releaseTime[0].required = true
      this.attachmentDialogVisible = true
    },
    deleteServe(data) {
      const isDeleteRelation =
        this.leftActiveType === '2' &&
        !this.activeTree.catalogName
      this.$confirm(
        `此操作将${
          isDeleteRelation
            ? '删除关联关系'
            : '永久删除该服务'
        }，是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        if (isDeleteRelation) {
          deletePictureInRelation(
            data.childId,
            data.mainPictureId
          ).then((res) => {
            // console.log('删除', res)
            if (res.success) {
              this.getRelationPicture()
              this.$message.success('删除关联关系成功')
            } else {
              this.$message.error(
                res.message || '删除关联关系失败'
              )
            }
          })
        } else {
          deleteAttachmentInCatalog({
            catalogId: this.activeTree.pkid,
            fileId: data.pkid
          }).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.getServeList()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
        }
      })
    },
    async onSubmitServe() {
      if (this.addServe) {
        if (!this.uploadList.length) {
          this.$message.error(
            `请上传${
              this.leftActiveType === '1' ? '文件' : '图片'
            }`
          )
          return
        }
        if (
          this.uploadList.some(
            (item) =>
              item.size / (1024 * 1024) >
              (this.leftActiveType === '1' ? 20 : 10)
          )
        ) {
          const exceed = this.uploadList.find(
            (item) =>
              item.size / (1024 / 1024) >
              (this.leftActiveType === '1' ? 20 : 10)
          )
          this.$message.warning(
            `${exceed.name}不能大于${
              this.leftActiveType === '1' ? 20 : 10
            }M`
          )
          return
        }
        // for await (const item of this.uploadList) {
        //   item.fileId = await this.uploadFile(item.raw)
        // }
        await Promise.all([
          ...this.uploadList.map((item) =>
            this.uploadFile(item)
          )
        ])
        addAttachmentToCatalog(
          this.uploadList.map((item) => {
            return {
              fileId: item.fileId,
              fileName: item.name,
              catalogId: this.activeTree.pkid,
              releaseTime: dayjs().format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }
          })
        ).then((res) => {
          // console.log(res)
          if (res.success) {
            this.getServeList()
            this.$message.success(
              `挂载${
                this.leftActiveType === '1'
                  ? '附件'
                  : '图片'
              }成功`
            )
            this.attachmentDialogVisible = false
            this.uploadList = []
          } else {
            this.$message.error(
              res.message ||
                `挂载${
                  this.leftActiveType === '1'
                    ? '附件'
                    : '图片'
                }失败`
            )
          }
        })
      } else {
        this.$refs.ruleFormServe.validate((valid) => {
          if (valid) {
            updateAttachmentInCatalog([
              {
                pkid: this.currentAttachment.pkid,
                fileName: this.serveForm.attachmentName,
                releaseTime: this.serveForm.releaseTime,
                remark:
                  this.leftActiveType === '2'
                    ? this.serveForm.remark
                    : null
              }
            ]).then((res) => {
              if (res.success) {
                this.$message.success('编辑成功')
                this.attachmentDialogVisible = false
                this.getServeList()
              } else {
                this.$message.error(
                  res.message || '编辑失败'
                )
              }
            })
          }
        })
      }
    },
    async uploadFile(item) {
      const formData = new FormData()
      formData.append('file', item.raw)
      await noticeFileUpload(formData).then((res) => {
        if (res.success) {
          item.fileId = res.data
          this.$forceUpdate()
        } else {
          this.$message.error(
            `文件${item.raw.name}${res.message}`
          )
        }
      })
    },
    // async uploadFile(file) {
    //   const formData = new FormData()
    //   formData.append('file', file)
    //   let fileId = ''
    //   await noticeFileUpload(formData).then((res) => {
    //     if (res.success) {
    //       fileId = res.data
    //     } else {
    //       this.$message.error(
    //         `文件${file.name}${res.message}`
    //       )
    //     }
    //   })
    //   return fileId
    // },
    getServeList() {
      retrieveAttachmentInCatalog({
        catalogId: this.activeTree.pkid,
        pageIndex: this.parameter.pageIndex,
        pageSize: this.parameter.pageSize
      })
        .then((res) => {
          if (res.success) {
            const list = res.data.list || []
            if (this.leftActiveType === '2') {
              list.forEach((item) => {
                item.type = this.activeTree.catalogName
              })
            }
            this.serveList = list
            this.total = res.data.count
            this.dragMode = 'list'
            this.rowDrag()
          } else {
            this.serveList = []
            this.$message.error(res.message)
          }
        })
        .catch((err) => {
          this.serveList = []
          console.error(err)
        })

      // 目录树处理
      if (this.leftActiveType === '2') {
        retrieveAttachmentInCatalog({
          catalogId: this.activeTree.pkid,
          pageIndex: 1,
          pageSize: 9999
        })
          .then((res) => {
            if (res.success) {
              const find = this.treeData.find(
                (item) => item.pkid === this.activeTree.pkid
              )
              find.children = res.data.list
            } else {
              this.$message.error(res.message)
            }
          })
          .catch((err) => {
            console.error(err)
          })
      }
    },
    // 获取关联图片数据
    getRelationPicture() {
      // this.rowDrag(true) // 禁用rowDrag
      this.dragMode = 'relation'
      this.rowDrag()
      retrievePictureInRelation({
        mainPictureId: this.activeTree.pkid
      })
        .then((res) => {
          if (res.success) {
            if (res.data.length) {
              const list = []
              res.data.forEach((relation) => {
                const picture = this.allPictureList.find(
                  (item) =>
                    item.pkid === relation.childPictureId
                )
                picture.type = relation.catalogName
                picture.childId = relation.childPictureId
                picture.mainPictureId =
                  // relation.mainPictureId
                  this.activeTree.pkid
                list.push(picture)
              })
              this.serveList = list
            } else {
              this.serveList = []
            }
          } else {
            this.serveList = []
            this.$message.error(res.message)
          }
        })
        .catch((err) => {
          this.serveList = []
          console.error(err)
        })
    },
    handleDrop(draggingNode, dropNode, dropType) {
      if (draggingNode.data.catalogName) {
        if (dropType === 'after') {
          const data = draggingNode.data
          data.frontId = dropNode.data.pkid
          treeUpdate({ ...data }, data.pkid).then((res) => {
            if (res.success) {
              this.$message.success(res.data)
            } else {
              this.$message.error(res.message)
            }
          })
        } else if (dropType === 'before') {
          const data = draggingNode.data
          data.frontId = -1
          treeUpdate({ ...data }, data.pkid).then((res) => {
            if (res.success) {
              this.$message.success(res.data)
            } else {
              this.$message.error(res.message)
            }
          })
        }
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      if (
        draggingNode.data.sourceName &&
        draggingNode.level === dropNode.level
      ) {
        if (
          draggingNode.data.catalogId ===
          dropNode.data.catalogId
        ) {
          if (dropNode.data.orderIndex === '0') {
            return type === 'prev' || type === 'next'
          } else {
            return type === 'next'
          }
        }
      }
      if (
        draggingNode.data.catalogName &&
        draggingNode.level === dropNode.level
      ) {
        if (
          draggingNode.data.parentId ===
          dropNode.data.parentId
        ) {
          if (dropNode.data.orderIndex === '0') {
            return type === 'prev' || type === 'next'
          } else {
            return type === 'next'
          }
        }
      } else {
        return false
      }
    },
    allowDrag() {
      return true
    },
    tableRowClassName({ _, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },
    // 附件拖动排序
    rowDrag(disable) {
      const el = document.querySelector(
        '.el-table__body-wrapper tbody'
      )
      const _this = this
      if (!_sortable) {
        _sortable = Sortable.create(el, {
          onEnd({ newIndex, oldIndex }) {
            // console.log(newIndex, oldIndex)
            if (newIndex === oldIndex) {
              return
            }
            // if (_this.leftActiveType === '1') {
            if (_this.dragMode === 'list') {
              const params = {
                catalogId: _this.activeTree.pkid,
                resourceId: _this.serveList[oldIndex].pkid,
                resourceType: 8,
                frontResourceId: ''
              }
              if (newIndex === 0) {
                params.frontResourceId = '-1'
              } else {
                if (newIndex > oldIndex) {
                  params.frontResourceId =
                    _this.serveList[newIndex].pkid
                } else {
                  params.frontResourceId =
                    _this.serveList[newIndex - 1].pkid
                }
              }
              updateAttachmentOrderInCatalog(params)
                .then((res) => {
                  _this.getServeList()
                  if (res.success) {
                    _this.$message.success('排序成功')
                  } else {
                    _this.$message.success(
                      res.message || '排序失败'
                    )
                  }
                })
                .catch((err) => {
                  console.error(err)
                  _this.$message.success('排序失败')
                  _this.getServeList()
                })
            } else {
              const params = {
                mainPictureId: _this.activeTree.pkid,
                childPictureId:
                  _this.serveList[oldIndex].pkid,
                frontId: ''
              }
              if (newIndex === 0) {
                params.frontId = '-1'
              } else {
                if (newIndex > oldIndex) {
                  params.frontId =
                    _this.serveList[newIndex].pkid
                } else {
                  params.frontId =
                    _this.serveList[newIndex - 1].pkid
                }
              }
              console.log('关联关系排序', params)
              updateRelationPicturesOrder(params)
                .then((res) => {
                  _this.getRelationPicture()
                  if (res.success) {
                    _this.$message.success('排序成功')
                  } else {
                    _this.$message.error(
                      res.message || '排序失败'
                    )
                  }
                })
                .catch((err) => {
                  console.error(err)
                  _this.$message.success('排序失败')
                  _this.getRelationPicture()
                })
            }
            // }
          }
        })
      }
      if (disable) {
        _sortable.option('disabled', disable)
      } else {
        _sortable.option('disabled', false)
      }
    },
    dialogClosed() {
      this.uploadList = []
    },
    relationPictureDialogClosed() {
      this.defaultCheckedIds = []
      this.deepClonedTreeData.forEach((item) => {
        item.children.forEach((picture) => {
          picture.checked = false
        })
      })
    },
    // 关联关系图片新增
    async onRelationPictureSubmit() {
      const checkedList = []
      this.deepClonedTreeData.forEach((item) => {
        checkedList.push(
          ...item.children.filter(
            (picture) =>
              picture.checked &&
              this.defaultCheckedIds.indexOf(
                picture.pkid
              ) === -1
          )
        )
      })
      if (!checkedList.length) {
        this.$message.error('请选择关联图片')
      } else {
        // console.log('添加关联图片', checkedList)
        const params = checkedList.map((item) => {
          return {
            mainPictureId: this.activeTree.pkid,
            childPictureId: item.pkid
          }
        })
        addPictureInRelation(params).then((res) => {
          if (res.success) {
            this.$message.success('添加关联图片成功')
            this.relationPictureDialogVisible = false
            this.getRelationPicture()
          } else {
            this.$message.error(
              res.message || '添加关联图片成功'
            )
          }
        })
      }
    },
    parseDateTime(dateTimeStr) {
      return new Date(dateTimeStr)
    }
  },
  watch: {
    treeData: {
      handler(val) {
        val.forEach((item) => {
          item.children.forEach((picture) => {
            picture.type = item.catalogName
          })
        })
      },
      deep: true
    }
  },
  computed: {
    uploadButtonDisabled() {
      if (this.leftActiveType === '1') {
        return (
          !this.activeTree ||
          !this.activeTree.parentId ||
          this.activeTree.parentId ===
            this.attachmentRootCatalogId
        )
      } else if (this.leftActiveType === '2') {
        return !this.activeTree
      } else {
        return true
      }
    },
    allPictureList() {
      const list = []
      this.deepClonedTreeData.forEach((item) => {
        list.push(...item.children)
      })
      return list
    },
    deepClonedTreeData() {
      const data = cloneDeep(this.treeData)
      data.forEach((item) => {
        item.children.forEach((picture) => {
          picture.checked = false
        })
      })
      return data
    }
  }
}
</script>

<style scoped lang="scss">
.body {
  width: calc(100% - 26px);
  height: calc(100% - 20px);
  margin: 10px 10px 10px 16px;
  background: #ffffff;
  box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.15);
  border-radius: 2px;

  ::v-deep.el-tree
    > .el-tree-node
    > .el-tree-node__content {
    padding-left: 8px !important;
  }

  ::v-deep.el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #f2f6fb;
    color: #497fa3;
  }

  ::v-deep.el-tree-node__content {
    height: 36px;
    font-size: 14px;
    // margin-top: 6px;
  }

  ::v-deep.el-tree-node__content:hover {
    background-color: #f2f6fb;
    color: #497fa3;
  }

  ::v-deep.light {
    background: #f9fcff;
    border: 1px solid #f2f6fb !important;
  }

  ::v-deep .el-tabs__item:focus.is-active {
    box-shadow: none !important;
  }

  // ::v-deep.el-button.update{
  //   background: #02a7f0;
  //   color: white !important;
  // }

  ::v-deep .el-dialog {
    height: 356px;

    &.upload-dialog {
      .el-dialog__body {
        height: calc(100% - 110px) !important;
        padding-bottom: 0 !important;

        .el-scrollbar {
          width: 100%;
          height: 100%;
        }
      }

      .el-dialog__footer {
        margin-top: 0;
      }
    }

    .el-dialog__header {
      background: #597182 !important;
      padding: 8px 0 14px 24px !important;
      height: 39px !important;

      .el-dialog__title {
        font-size: 16px !important;
        line-height: 22px;
        font-weight: 400 !important;
        color: white !important;
        //margin:19px 0 14px 24px !important;
      }

      .el-dialog__headerbtn {
        font-size: 16px;
        top: 10px !important;
        right: 17px !important;
        color: white !important;

        .el-dialog__close {
          color: white !important;
        }
      }
    }

    .el-dialog__body {
      padding: 17px 32px 18px 26px !important;
      height: calc(100% - 150px);

      .el-form-item {
        margin-bottom: 19px !important;
      }
    }

    .el-dialog__footer {
      margin-top: 30px;
    }

    .el-select
      .el-select__tags
      + .el-input
      .el-input__inner {
      height: auto !important;
      background-color: #f6f9fc !important;
    }

    .el-input__inner {
      height: 34px !important;
      background-color: #f6f9fc !important;
    }

    .el-button--default {
      border-color: #497fa3 !important;

      span {
        color: #497fa3 !important;
      }
    }

    .el-button--primary {
      background: #497fa3 !important;
      border-color: white !important;
    }
  }

  ::v-deep .el-pagination {
    .active {
      background: #f6f9fc !important;
      color: #00baff !important;
    }

    button {
      border: 1px solid #ebf1f8 !important;
      background: white !important;
      color: #a7adb5 !important;
    }

    li {
      background: white !important;
      color: #00baff !important;
      border: 1px solid #ebf1f8;
      border-radius: 2px;
      font-weight: 400 !important;
      font-size: 12px !important;
      line-height: 25px !important;
    }
  }

  .body_left {
    width: 22%;
    height: 100%;
    background: white;
    padding: 15px 0;
    // margin-right: 10px;
    border: 1px solid #f2f6fb;
    box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.05);

    .body_left_header {
      width: 100%;
      height: 45px;
      font-size: 16px;
      color: #4c565c;
      line-height: 33px;

      .half {
        width: 50%;
        height: 100%;
        display: inline-block;
        text-align: center;
        cursor: pointer;

        :hover {
          color: #497fa3;
          font-weight: bold;
        }

        .iconfont {
          font-size: 16px;
          color: #4c565c;
        }

        &-active {
          // background-color: #497fa3;
          color: #497fa3;
          font-weight: bold;
        }

        span {
          margin-left: 6px;
        }
      }
    }

    .body_left_tab {
      width: 100%;
      height: 49px;
      background: #f2f6fb;
      border: 1px solid #f2f6fb;
      padding: 8px 5%;

      .tab_item {
        width: 33%;
        height: 100%;
        display: inline-block;
        text-align: center;
        cursor: pointer;
        font-size: 14px;
        color: #4c565c;
        line-height: 31px;
        position: relative;
      }

      .tab_item:hover {
        color: #497fa3;
      }

      .tab_item:nth-child(3)::before {
        content: '|';
        display: inline-block;
        float: left;
        color: #d0d8e1;
      }

      .tab_item:nth-child(2)::before {
        content: '|';
        display: inline-block;
        float: left;
        color: #d0d8e1;
      }

      .tab_item_active {
        width: 33%;
        height: 100%;
        color: #497fa3;
        position: relative;
      }

      .tab_item_active::after {
        content: '';
        position: absolute;
        left: 38%;
        bottom: 0;
        width: 24%;
        height: 2px;
        background: #497fa3;
      }
    }

    .body_tree {
      width: 100%;
      height: calc(100% - 100px);
      padding-top: 6px;
      overflow: auto;

      .topic-item:hover {
        background: #497fa3;
        color: #ffffff;
      }

      .topic-item {
        width: 60%;
        margin-left: 20%;
        height: 40px;
        line-height: 40px;
        color: #497fa3;
        font-size: 16px;
        text-align: center;
        border: 1px #497fa3 solid;
        border-radius: 4px;
        margin-top: 20px;
        cursor: pointer;

        &-active {
          background: #497fa3;
          color: #ffffff;
        }
      }
    }
  }

  &_right {
    width: calc(78% - 3px);
    margin-left: 3px;
    background: white;
    padding: 15px 30px;

    .half {
      width: 30%;
      height: 100%;
      display: inline-block;
      vertical-align: middle;
      box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.05);
      padding: 5px;
      // overflow: auto;
      .half-title {
        height: 40px;
        line-height: 40px;
        padding-left: 12px;
        font-size: 16px;
        // border-bottom: 1px #4c565c solid;
      }

      .half-body {
        height: calc(100% - 40px);
        overflow: auto;

        ::v-deep .el-table__row {
          .el-table__cell {
            padding: 8px !important;
            color: #4c565c;
          }
        }
      }
    }

    .body_right_header {
      width: 100%;
      height: 45px;

      .el-button {
        background: #497fa3 !important;
        color: white !important;
        border: none !important;
        border-radius: 2px;
        padding: 8px 9px;
      }

      .header_right {
        float: right;
        display: inline-block;
        // width: 60%;
        height: 100%;
      }

      .header_right::v-deep {
        .el-input__inner {
          // background: #f6f9fc !important;
          color: #a7adb5 !important;
          height: 32px !important;
          width: 228px !important;

          .el-input__icon {
            width: 16px !important;
            height: 16px !important;
            font-size: 16px !important;
          }
        }

        .el-input__suffix {
          top: 1px !important;
          right: 8px !important;
        }

        .el-select {
          .el-input__inner {
            width: 170px !important;
            margin-left: 10px;
          }

          .el-input__suffix {
            top: 4px !important;
          }

          .is-focus {
            .el-input__suffix {
              top: -3px !important;
            }
          }
        }

        .el-cascader {
          top: -4px;

          .el-input__inner {
            width: 170px !important;
            margin-left: 10px;
          }
        }
      }
    }

    ::v-deep .el-table__row {
      .el-table__cell {
        padding: 0 !important;
        color: #4c565c;
      }
    }
  }
}

::v-deep {
  .el-tabs {
    // 居中
    //&__nav-scroll {
    //  width: 50%;
    //  margin: 0 auto;
    //}

    //&__header {
    //  margin-left: 20px;
    //}

    &__nav-wrap::after {
      position: static !important;
    }

    &__active-bar {
      background-color: #497fa3;
    }

    &__item {
      &.is-active {
        color: #497fa3;
      }

      &:not(:last-of-type) {
        &:after {
          content: '';
          height: 30%;
          width: 1px;
          position: absolute;
          right: 0;
          top: 35%;
          background-color: #d0d8e1;
        }
      }
    }
  }
}

.configType {
  &-title {
    display: flex;
    height: 33px;
    line-height: 33px;
    font-weight: 600;
    color: #ffffff;
    margin-bottom: 7px;

    > div {
      position: relative;
      margin-right: 20px;
      /*padding-bottom: 10px;*/
      cursor: pointer;
      font-size: 14px;
      // text-shadow: 0px 2px 2px #0C141D;
      background: #606266;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;

      &:first-child {
        // margin-left: 10px;
      }
    }

    .is-active {
      background: rgb(0, 152, 255);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;

      &::after {
        content: '';
        position: absolute;
        left: 25%;
        bottom: 0;
        width: 50%;
        height: 2px;
        background: rgb(0, 152, 255);
      }
    }
  }
}

.dialog-line {
  width: 600px;
  height: 1px;
  border-top: 1px solid #d0d8e1;
  margin: 0 0 10px -25px;
}
</style>
